import React from "react";
import {withRouter} from 'react-router-dom'
import {log} from "../../../utils/commonfunc";
import LocalStorageService from "../../../utils/LocalStorageService";
import {pushWithSearch, searchParams} from "../../mall/mall";
import {
    fetchMarkGameListReq,
    getEuroPlanDetailReq,
    getPlanDetailReq, getUserDetailReq,
    jubaoEuroPlanReq, supportEuroPlanReq,
    zanEuroPlanReq
} from "../../../apis/goApis";
import GoBackLayout from "../../../layouts/GoBackLayout/GoBackLayout";
import shareSrc from "../../../res/images/web/euro/share@2x.png"
import PlanCard from "../../plan-detail/plan-card/plan-card";
import PlanItem from "../../game-room/components/Main/plan/plan_item/plan_item";
import reasonBlock from "../../../res/images/web/euro/方案详情@2x.png"
import jubaoSrc from "../../../res/images/web/euro/举报@2x.png"
import yijubaoSrc from "../../../res/images/web/euro/已举报@2x.png"
import zanSrc from "../../../res/images/web/euro/赞@2x.png"
import yizanSrc from "../../../res/images/web/euro/已赞@2x.png"
import {Modal, Toast} from "antd-mobile";
import CountDisplay from "../../game-room/components/Main/chat-room/GiftPopup/GiftCount/CountDisplay/CountDisplay";
import {checkAndGoBack} from "../../best-line-up/best-line-up";
import addGoldSrc from "../../../res/images/web/euro/btn／add@2x.png"
import {addLinkAndClick} from "../../GradePlayer/GradePlayer";
import constant, {test,} from "../../../utils/constants";

class EuroPlan extends React.Component {
    constructor(props) {
        super(props)
        this.planId = parseInt(this.props.match.params.id)
        this.searchParams = searchParams()
        this.voteHome = this.props.location.state?.home
        this.webview = this.searchParams.webview === 'true'
        this.uid = this.searchParams.webview === 'true' ? this.searchParams.uid : LocalStorageService.get('userid')
        this.state = {
            game: null,
            marked: false,
            plan: null,
            zan: false,
            jubao: false,
            price: 0,
            gold: 0,
            pack: 1,
            modal: {
                zan: false,
                jubao: false,
                support: false,
            }
        }
    }

    componentDidMount() {
        if (this.uid) {
            this.getUser()
            this.getDetail()
            this.getMarked()
        }

    }

    getUser = () => {
        getUserDetailReq({
            Uid: this.uid,
        }).then(res => {
            const data = res.data
            if (data.ok) {
                this.setState({
                    gold: data.ok.Gold,
                })
            }
        })
    }

    getDetail = () => {
        const params = {
            Matchid: this.planId,
            Uid: this.uid,
        }
        getEuroPlanDetailReq(params)
            .then(res => {
                const data = res.data
                if (data.ok) {
                    const ozb = data.ozb
                    const scheme = data.scheme
                    const game = {
                        Zhuname: [ozb.Zhuname],
                        Kename: [ozb.Kename],
                        Matchname: ['欧洲杯'],
                        Zhulogo: ozb.Zhuimg,
                        Kelogo: ozb.Keimg,
                        Zhufen: ozb.Zhufen,
                        Kefen: ozb.Kefen,
                        State: ozb.State,
                        Startt: ozb.Startt,
                        Count: ozb.Count,
                    }
                    const plan = {
                        id: scheme.Uid,
                        icon: scheme.Avatar,
                        name: scheme.Name,
                        goodAt: scheme.Goodat,
                        reason: this.voteHome ? scheme.Zhureason : scheme.Kereason,
                        red: this.voteHome ? scheme.Awardzhu : scheme.Awardke,
                        Uid: this.voteHome ? scheme.Uid1 : scheme.Uid2,
                    }
                    let zan = false
                    let jubao = false
                    if (this.voteHome) {
                        jubao = data.zanjubao.Jubao.length > 0
                        zan = data.zanjubao.Zan > 0
                    } else {
                        jubao = data.zanjubao.Jubaoke.length > 0
                        zan = data.zanjubao.Zanke > 0
                    }
                    this.setState({
                        game,
                        plan,
                        jubao,
                        zan,
                        price: data.paygold,
                    })
                }
                log(data)
            })
    }

    getMarked = () => {
        const uid = this.uid
        fetchMarkGameListReq({
            uid,
        }).then((resp) => {
            let marked = false
            const list = resp.data.ok
            list.map(idList => {
                if (idList.length > 1) {
                    if (idList.findIndex(id => id === String(this.matchId)) > -1) {
                        marked = true
                    }
                }
            })
            this.setState({
                marked,
            })
        })
    }

    goBack = () => {
        checkAndGoBack(this.props.history)
    }

    callModal = (key) => {
        this.setState({
            modal: {
                ...this.state.modal,
                [key]: true,
            }
        })
    }

    cancelModal = (key) => {
        this.setState({
            modal: {
                ...this.state.modal,
                [key]: false,
            }
        })
    }

    onPackChange = (offset) => {
        let pack = this.state.pack + offset
        if (pack < 0) {
            pack = 0
        }
        this.setState({
            pack,
        })
    }

    zan = () => {
        zanEuroPlanReq({Uid: this.uid, Matchid: this.planId, Who: this.voteHome ? 'zhu' : 'ke'})
            .then(res => {
                const data = res.data
                if (data.ok) {
                    log(data)
                    this.setState({
                        zan: true,
                    }, () => {
                        Toast.info('赞成功', 0.5)
                    })
                }
            })
    }

    jubao = () => {
        Modal.alert('确定举报\n' + '该分析内容吗？', '', [
            {
                text: '举报',
                onPress: () => {
                    jubaoEuroPlanReq({Uid: this.uid, Matchid: this.planId, Who: this.voteHome ? 'zhu' : 'ke'})
                        .then(res => {
                            const data = res.data
                            if (data.ok) {
                                log(data)
                                this.setState({
                                    jubao: true,
                                }, () => {
                                    Toast.info('举报成功', 0.5)
                                })
                            }
                        })
                },
            },
            {text: <span style={{color: 'black',}}>点错了</span>, onPress: () => {} },
        ])
    }

    support = () => {
        const params = {
            Uid: this.uid,
            Matchid: this.planId,
            Count: this.state.pack,
            Who: this.voteHome ? 'zhu' : 'ke',
        }

        const gold = this.state.gold
        const total = this.state.pack * this.state.price

        if (gold < total || gold === 0) {
            Modal.alert('金币不足是否前往充值？', '', [
                {
                    text: '取消',
                    onPress: () => {},
                },
                {
                    text: <span style={{color: '#FFA500',}}>去充值</span>,
                    onPress: () => {
                        if (this.searchParams.webview === 'true') {
                            let base = 'http://www.youtoball.com:8080/'
                            if (test) {
                                base = 'http://123.207.85.242:8080/'
                            }
                            addLinkAndClick(base + 'wallet')
                        } else {
                            pushWithSearch(this.props.history, '../wallet')
                        }
                        this.cancelModal('support')
                        checkAndGoBack(this.props.history, './my-euro-plan')
                    },
                },
            ])
        } else {
            supportEuroPlanReq(params)
                .then(res => {
                    const data = res.data
                    if (data.ok) {
                        this.cancelModal('support')
                        Toast.success('支持成功', 0.5)
                        setTimeout(() => this.getUser(), 500)
                    } else if (data.err) {
                        Toast.fail(constant.ErrorCode[data.err], 0.5)
                    }
                })
        }

    }

    goToAddGold = () => {
        const end = test ? 'http://123.207.85.242:8080/wallet' : 'http://www.youtoball.com:8080/wallet'
        addLinkAndClick(end)
        checkAndGoBack(this.props.history, './my-euro-plan')
    }

    goToPro = () => {
        const game = this.state.game
        const plan = this.state.plan
        log(plan)
        const end = test ? 'http://123.207.85.242:8080/' : 'http://www.youtoball.com:8080/'
        if (this.searchParams.webview === 'true') {
            addLinkAndClick(end + 'plan-pro-detail-page/' + plan.Uid)
        } else {
            this.props.history.push('../plan-pro-detail-page/' + plan.Uid)
        }
    }

    render() {


        let rightShare = <img src={shareSrc} alt='' style={{width: 28, height: 29}}/>
        const game = this.state.game
        const marked = this.state.marked
        const plan = this.state.plan
        const voteHome = this.voteHome

        const reasonTemplate = (
            <div className='euro-plan-detail-container'>
                <div className='euro-plan-detail-title'>
                    <img src={reasonBlock} alt=''/>
                    <span>方案详情</span>
                </div>
                <div className='euro-plan-detail-content'>
                    <p style={{
                        fontSize: '14px',
                        fontWeight: 500,
                        color: '#333333',
                        lineHeight: '20px',
                        marginBottom: '8px',
                    }}>支持{plan && (voteHome ? game.Zhuname : game.Kename)}</p>
                    <p style={{
                        fontSize: '14px',
                        fontWeight: '400',
                        color: 'rgba(51, 51, 51, 0.8)',
                        lineHeight: '20px',
                    }}>{plan && plan.reason}</p>
                </div>
            </div>
        )

        const buttons = (
            <div className='euro-plan-detail-bottom'>
                <img src={this.state.jubao ? yijubaoSrc : jubaoSrc} alt='' onClick={this.jubao}/>
                {/*<img src={jubaoSrc} alt=''/>*/}
                <div style={{position: 'relative', margin: '0 8px',}} className='flex-1'>
                    <button
                        onClick={() => {
                            this.getUser()
                            this.callModal('support')
                        }}
                    >我要支持</button>
                    <div className='euro-plan-detail-bottom-gold'>
                        <span>我的金币：{this.state.gold}</span>
                        <img src={addGoldSrc} alt='' onClick={this.goToAddGold}/>
                    </div>
                </div>

                <img src={this.state.zan ? yizanSrc : zanSrc} alt='' onClick={this.zan}/>

            </div>
        )

        const supportModal = <Modal
            visible={this.state.modal.support}
            maskClosable
            // popup
            transparent
            onClose={() => this.cancelModal('support')}
            footer={[
                {
                    text: '取消',
                    onPress: () => this.cancelModal('support'),
                },
                {
                    text: <span style={{color: '#FFA500',}}>确定</span>,
                    onPress: () => this.support(),
                },
            ]}
        >
            <p
                style={{
                    fontSize: '16px',
                    fontWeight: 500,
                    color: '#333333',
                    lineHeight: '22px',
                    marginBottom: '8px',
                }}
            >是否消耗 {plan && this.state.price * this.state.pack} 金币，支持方案？</p>
            <p
                style={{
                    fontSize: '14px',
                    fontWeight: 400,
                    color: 'rgba(51, 51, 51, 0.4)',
                    lineHeight: '14px',
                    marginBottom: '32px',
                }}
            >方案若翻红，可获得{plan && this.state.pack * plan.red}应豆</p>
            <CountDisplay
                total={this.state.pack}
                countWidth={112}
                changeTotal={this.onPackChange}
            />

        </Modal>

        return (
            <>
                {supportModal}
                <GoBackLayout
                    history={this.props.history}
                    onLeftClick={this.goBack}
                    mainTitle='详情'
                    // rightContent={rightShare}
                >
                    <div className="mg-b-4px">
                        {game && <PlanCard
                            noPrefix
                            game={game}
                            marked={marked}

                        />}
                    </div>
                    {plan && <PlanItem planDate={plan}
                                       fromDetail
                                       dontNavigateToDetail
                                       proEnd={'../plan-pro-detail-page/' + plan.Uid}
                                       hideGoToPro={true}
                    />}
                    {plan && reasonTemplate}
                    {plan && buttons}
                </GoBackLayout>
            </>
        )
    }
}

export default withRouter(EuroPlan)